package com.nononsenseapps.feeder.ui.category

import androidx.lifecycle.viewModelScope
import cn.ekuma.odbo.mobile.category.ui.OnTreeNodeListener
import cn.ekuma.odbo.mobile.category.ui.SampleCategoryItemAdapter
import com.nononsenseapps.feeder.db.view.PreviewItem
import com.nononsenseapps.feeder.model.GlobalViewModel
import com.nononsenseapps.feeder.model.category.FeedItemCategoryHelper
import com.nononsenseapps.feeder.ui.feed.FeedItemsViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch


class FeedItemTagTreeAdapter(val globalViewModel: GlobalViewModel,val feedItemsViewModel: FeedItemsViewModel, onTreeNodeListener: OnTreeNodeListener): SampleCategoryItemAdapter(onTreeNodeListener) {

    private var currentTreeEntry:String?=null

    fun changeTagTreeType(openTreeID:String){
        FeedItemCategoryHelper.getTreeItem(openTreeID)?.let{
            currentTreeEntry = it.id
            flushTreeAdapter()
        }
    }

    fun submitData(feedItemList:List<PreviewItem>){
        globalViewModel.changeCurrentItemList(feedItemList)
        currentTreeEntry?.let {
            val rootTree=FeedItemCategoryHelper.buildTreeCategoryRoot(it)
            FeedItemCategoryHelper.initTreeFeedItemList(rootTree,feedItemList)
            this.subject(rootTree)
        }
    }

    private fun flushTreeAdapter(){
        feedItemsViewModel.viewModelScope.launch {
            feedItemsViewModel.listCurrentFeedItems().flowOn(Dispatchers.Main).collect {
                    submitData(it)
                }
         }
    }
}